package com.xinlan.imageeditlibrary;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.viewpager.widget.ViewPager;

import com.baselibrary.MessageBus;
import com.baselibrary.manager.AppManager;
import com.baselibrary.utils.EventBusUtils;
import com.baselibrary.utils.HKToastUtils;
import com.baselibrary.utils.MediaFileUtils;
import com.xinlan.imageeditlibrary.editimage.model.OnNextStepClickListener;
import com.xinlan.imageeditlibrary.editimage.utils.BaseUtils;
import com.xinlan.imageeditlibrary.editimage.utils.BitmapUtils;

import java.io.File;
import java.util.ArrayList;

/**
 * @author 关忆北、
 * @description 图片编辑
 * @time 2022/5/26 11:33 上午
 */
public class EditImgMainActivity extends AppCompatActivity implements OnNextStepClickListener {
    public static final String FILE_PATH_LIST = "file_path_list";
    public static final int RESULTCODE_PICTURE = 102;
    public static final int RESULT_PICTURE = 101;
    public static final int RESULT_EDITIMGOVVER = 202;
    private LinearLayout mLlClose;
    public ViewPager mVpEdit;
    private ArrayList<String> mImgPathList = new ArrayList<>();//图片路径集合
    // private ArrayList<String> mSaveFilePath = new ArrayList<>();//新图片路径
    private Dialog dialog;
    private int saveFilePathCount, mSelectedPos;
    String mAlbumScheme = "scheme://release/releaseImgVideo";//相册选择界面
    String mDynamicScheme = "scheme://main/mainReleaseImgVideo";//发布界面
    public ArrayList<EditImageFragment> mListFragment;
    private static final String TAG = "EditImgMainActivity";
    private boolean isForResult;
    private TextView mTvEditIndex;
    //是否通过eventbus 传值
    private boolean isPassEventbus;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_img_main);
        setStatusBarFullTransparent();
        MediaFileUtils.addActivity(this);
        if (ActivityCompat.checkSelfPermission(EditImgMainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(EditImgMainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
        initView();
        initListener();
        initData();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (mListFragment.get(mSelectedPos).mPaintFragment.mPopPaint != null) {
            if (mListFragment.get(mSelectedPos).mPaintFragment.mPopPaint.isShowing()) {
                mListFragment.get(mSelectedPos).mPaintFragment.mPaintView.onTouchEvent(event);
                return true;
            }
        }
        return super.dispatchTouchEvent(event);
    }

    private void initData() {
        isForResult = getIntent().getBooleanExtra("isForResult", false);
        isPassEventbus = getIntent().getBooleanExtra("isPassEventbus", false);
        mImgPathList = getIntent().getStringArrayListExtra(FILE_PATH_LIST);//这里的集合永远都是 1
        mListFragment = new ArrayList<>();
        for (String s : mImgPathList) {
            Bundle mBundle = new Bundle();
            mBundle.putString(EditImageFragment.FILE_PATH, s);
            mBundle.putString(EditImageFragment.EXTRA_OUTPUT, s);
            Log.d(TAG, "输出路径: " + s);
            EditImageFragment mEditImageFragment = EditImageFragment.newInstance(isPassEventbus,this, this);
            mEditImageFragment.setArguments(mBundle);
            mListFragment.add(mEditImageFragment);
        }
        EditImagePagerAdapter tabPagerAdapter = new EditImagePagerAdapter(getSupportFragmentManager());
        tabPagerAdapter.setList(mListFragment);
        mVpEdit.setAdapter(tabPagerAdapter);
        mVpEdit.setCurrentItem(0);
        mVpEdit.setOffscreenPageLimit(mListFragment.size());


        mTvEditIndex.setVisibility(mImgPathList.size() > 1 ? View.VISIBLE : View.GONE);
        mTvEditIndex.setText(1 + "/" + mImgPathList.size());
    }

    private void initView() {
        mTvEditIndex = findViewById(R.id.tv_edit_index);
        mLlClose = findViewById(R.id.ll_close);
        mVpEdit = findViewById(R.id.vp_edit);
        dialog = BaseUtils.getLoadingDialog(EditImgMainActivity.this);
        mVpEdit.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mSelectedPos = position;
                mTvEditIndex.setText((position + 1) + "/" + mImgPathList.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initListener() {
        mLlClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mListFragment.get(mSelectedPos).getOnBackPressedCallBack().onBack();
            }
        });
    }


    @Override
    public void onBackPressed() {
        mListFragment.get(mSelectedPos).getOnBackPressedCallBack().onBack();


    }

    @Override
    public void onNextStepClick() {
        for (int i = 0; i < mListFragment.size(); i++) {
            SaveImageTask saveImageTask = new SaveImageTask(mImgPathList.get(i));
            saveImageTask.execute(mListFragment.get(i).getMainBit());
        }
    }

    public void onSetEnabled() {
        for (int i = 0; i < mListFragment.size(); i++) {
            mListFragment.get(i).mTvQueDing.setEnabled(true);
        }
    }

    @Override
    public void onSaveTaskDone() {
//        if (!BuildConfig.DEBUG) {
        //回传发布界面
        saveFilePathCount = 0;
        if (isForResult) {
            Intent i = new Intent();
            i.putExtra(EditImageFragment.EXTRA_OUTPUT, mImgPathList);
            i.putExtra("isPassEventbus", isPassEventbus);
            setResult(EditImgMainActivity.RESULTCODE_PICTURE, i);
            finish();
            return;
        }
        if (isPassEventbus){
            //通过eventbus传值
            EventBusUtils.sendNotify1Value(MessageBus.msgId_select_img_video_path_list,mImgPathList);
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mDynamicScheme));
        intent.putExtra("result", mImgPathList);
        intent.putExtra("Dynamictype", 1);
        startActivity(intent);

//        } else {
//            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mAlbumScheme));
//            intent.putExtra(EditImageFragment.EXTRA_OUTPUT, mImgPathList);
//            setResult(RESULTCODE_PICTURE, intent);
//            finish();
//        }
    }

    /**
     * 保存图像
     * 完成后退出
     */
    private class SaveImageTask extends AsyncTask<Bitmap, Void, Boolean> {

        private final String saveFilePath;


        public SaveImageTask(String saveFilePath) {
            this.saveFilePath = saveFilePath;
        }

        @Override
        protected Boolean doInBackground(Bitmap... params) {
            if (TextUtils.isEmpty(saveFilePath))
                return false;

            return BitmapUtils.saveBitmap(params[0], saveFilePath);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            if (dialog != null && dialog.isShowing() && AppManager.isValidActivity(EditImgMainActivity.this)) {
                dialog.dismiss();
            }
        }

        @Override
        protected void onCancelled(Boolean result) {
            super.onCancelled(result);
            if (dialog != null && dialog.isShowing() && AppManager.isValidActivity(EditImgMainActivity.this)) {
                dialog.dismiss();
            }
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //如果当前Activity没有被销毁
            if (dialog != null && AppManager.isValidActivity(EditImgMainActivity.this)) {
                dialog.show();
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);

            if (result) {
                saveFilePathCount++;
                if (saveFilePathCount == mImgPathList.size()) {
                    if (dialog != null && dialog.isShowing() && AppManager.isValidActivity(EditImgMainActivity.this)) {
                        dialog.dismiss();
                    }
                    onSaveTaskDone();
                    onSetEnabled();
                }
            } else {
                if (dialog != null && dialog.isShowing() && AppManager.isValidActivity(EditImgMainActivity.this)) {
                    dialog.dismiss();
                }
                onSetEnabled();
//                Toast.makeText(EditImgMainActivity.this, R.string.save_error, Toast.LENGTH_SHORT).show();
                HKToastUtils.showToast(R.string.save_error);
            }
        }

    }//end inner class

    /**
     * 全透状态栏
     */
    protected void setStatusBarFullTransparent() {
        //21表示5.0
        Window window = getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);
    }
}
